package com.rico.smart.device;



import com.rico.smart.message.IMessage;
import com.rico.smart.message.MessageType;
import com.rico.smart.socket.MessageHandler;
import com.rico.smart.socket.SocketConnection;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class DeviceManager implements MessageHandler {

    protected String TAG="DeviceManager";

   private LinkedHashMap<String,Device> deviceLinkedHashMap =new LinkedHashMap<>();


   private List<Device> deviceList =new ArrayList<>() ;

   private static DeviceManager instance;

   private List<DeviceManagerListener> deviceManagerListeneres=new ArrayList<DeviceManagerListener>();

   private DeviceManager(){
      init();
   }

   public static DeviceManager getInstance(){
       if(instance==null){
           instance=new DeviceManager();

       }
       return instance;
   }

   private void init(){

   }

   public void put(Device device){
       if(device.getDeviceInfo()==null){
           return;
       }
       if(deviceLinkedHashMap.get(device.getDeviceInfo().getDeviceId())!=null){
           return;
       }
       deviceList.remove(device);
       deviceLinkedHashMap.put(device.getDeviceInfo().getDeviceId(),device);
       deviceList.add(device);
       device.addMessageHandler(this);
   }

    public Device get(String deviceId){
        return deviceLinkedHashMap.get(deviceId);
    }


    public List<Device> getDeviceList(){
        return deviceList;
    }

    public List<DeviceInfo> getDeviceInfoList(){
       ArrayList<DeviceInfo> list=new ArrayList<DeviceInfo>();
       for(Device device:this.deviceList){
           DeviceInfo di=new DeviceInfo();
           di.setDeviceId(device.getDeviceInfo().getDeviceId() );
           di.setLocalIP(device.getDeviceInfo().getLocalIP());
           di.setLocalPort(device.getDeviceInfo().getLocalPort());
           list.add(di);
       }
       return list;
    }

    public void addDeviceManagerListener(DeviceManagerListener deviceManagerListener) {
        this.deviceManagerListeneres.add(deviceManagerListener);
    }

    @Override
    public void onMessageReceived(SocketConnection socket, IMessage message) {
        if(message.getMessageType()== MessageType.SUCCESS){
            for(DeviceManagerListener deviceManagerListener: deviceManagerListeneres){
                deviceManagerListener.onDeviceChange();
            }
        }
    }

    @Override
    public void onReceivedMessageError(SocketConnection socketThread, Exception e) {

    }

    public interface DeviceManagerListener{
       public void onDeviceChange();
    }
    public void addDeviceList(List<DeviceInfo> deviceList){
      for(DeviceInfo item:deviceList){
          this.put(new Device(item));
      }
    }
}
